<template>
  <n-date-picker v-model:value="dateValue" :value-format="valueFormat" @update:formatted-value="updateValue">
  </n-date-picker>
</template>
<script lang="tsx" setup>
import { Ref, ref } from 'vue';
import { format } from 'date-fns';

type TDate = number | string

const props = defineProps<{
  value: TDate | [TDate, TDate],
  valueFormat?: string,
  valueType?: 'timestamp' | 'formatted',
}>();

const emits = defineEmits(['update:value']);

const getTime = (t) => new Date(t).getTime();
const valueFormat = props.valueFormat || 'yyyy-MM-dd';
const valueType = props.valueType || 'formatted';

const updateValue = (fv, tv) => {
  const value = valueType === 'formatted' ? fv : tv;
  emits('update:value', value);
}

let dateValue: Ref<number[]> | Ref<number>;

if (Array.isArray(props.value)) {
  dateValue = ref([getTime(props.value[0]).valueOf(), getTime(props.value[1]).valueOf()]);
  updateValue([format(dateValue.value[0], valueFormat), format(dateValue.value[1], valueFormat)], dateValue);
}
else {
  dateValue = ref(getTime(props.value).valueOf());
  updateValue(format(dateValue.value, valueFormat), dateValue);
}

</script>